const db = require('../config/database');
const { successResponse, errorResponse } = require('../utils/response');

/**
 * 获取宠物信息
 */
const getPetInfo = async (req, res) => {
    try {
        const userId = req.user.id;
        
        const [pets] = await db.execute(
            'SELECT * FROM pets WHERE user_id = ?',
            [userId]
        );
        
        if (pets.length === 0) {
            return errorResponse(res, '宠物不存在', 404);
        }
        
        const pet = pets[0];
        
        // 计算宠物状态衰减（基于时间）
        const now = new Date();
        const lastFed = pet.last_fed ? new Date(pet.last_fed) : new Date(pet.created_at);
        const lastPlayed = pet.last_played ? new Date(pet.last_played) : new Date(pet.created_at);
        
        const hoursSinceFed = Math.floor((now - lastFed) / (1000 * 60 * 60));
        const hoursSincePlayed = Math.floor((now - lastPlayed) / (1000 * 60 * 60));
        
        // 每小时减少5点饥饿值和快乐值
        let hunger = Math.max(0, pet.hunger - hoursSinceFed * 5);
        let happiness = Math.max(0, pet.happiness - hoursSincePlayed * 5);
        let health = Math.max(0, Math.min(100, (hunger + happiness) / 2));
        
        // 更新数据库中的值
        if (hunger !== pet.hunger || happiness !== pet.happiness || health !== pet.health) {
            await db.execute(
                'UPDATE pets SET hunger = ?, happiness = ?, health = ? WHERE user_id = ?',
                [hunger, happiness, health, userId]
            );
        }
        
        return successResponse(res, {
            ...pet,
            hunger,
            happiness,
            health
        });
        
    } catch (error) {
        console.error('获取宠物信息错误:', error);
        return errorResponse(res, '获取宠物信息失败', 500, error);
    }
};

/**
 * 喂养宠物
 */
const feedPet = async (req, res) => {
    const connection = await db.getConnection();
    
    try {
        await connection.beginTransaction();
        
        const userId = req.user.id;
        const { foodType = 'basic' } = req.body;
        
        // 不同食物消耗不同星星
        const foodCost = {
            'basic': 2,      // 基础食物
            'premium': 5,    // 高级食物
            'deluxe': 10     // 豪华食物
        };
        
        const cost = foodCost[foodType] || 2;
        
        // 检查用户星星是否足够
        const [users] = await connection.execute(
            'SELECT stars FROM users WHERE id = ?',
            [userId]
        );
        
        if (users[0].stars < cost) {
            await connection.rollback();
            return errorResponse(res, '星星不足', 400);
        }
        
        // 扣除星星
        await connection.execute(
            'UPDATE users SET stars = stars - ? WHERE id = ?',
            [cost, userId]
        );
        
        // 增加饥饿值
        const hungerIncrease = {
            'basic': 20,
            'premium': 40,
            'deluxe': 60
        };
        
        await connection.execute(
            `UPDATE pets 
             SET hunger = LEAST(100, hunger + ?), 
                 health = LEAST(100, (hunger + ?) / 2 + happiness / 2),
                 last_fed = NOW()
             WHERE user_id = ?`,
            [hungerIncrease[foodType], hungerIncrease[foodType], userId]
        );
        
        // 更新每日任务
        await connection.execute(
            'CALL update_daily_task(?, ?)',
            [userId, 'feed_pet']
        );
        
        await connection.commit();
        
        // 获取更新后的宠物信息
        const [pets] = await connection.execute(
            'SELECT * FROM pets WHERE user_id = ?',
            [userId]
        );
        
        return successResponse(res, pets[0], '喂养成功！宠物很开心~');
        
    } catch (error) {
        await connection.rollback();
        console.error('喂养宠物错误:', error);
        return errorResponse(res, '喂养宠物失败', 500, error);
    } finally {
        connection.release();
    }
};

/**
 * 与宠物玩耍
 */
const playWithPet = async (req, res) => {
    const connection = await db.getConnection();
    
    try {
        await connection.beginTransaction();
        
        const userId = req.user.id;
        
        // 检查是否有足够能量（饥饿值要大于30）
        const [pets] = await connection.execute(
            'SELECT * FROM pets WHERE user_id = ?',
            [userId]
        );
        
        if (pets.length === 0) {
            await connection.rollback();
            return errorResponse(res, '宠物不存在', 404);
        }
        
        if (pets[0].hunger < 30) {
            await connection.rollback();
            return errorResponse(res, '宠物太饿了，先喂它吧~', 400);
        }
        
        // 玩耍：增加快乐值，减少少量饥饿值
        await connection.execute(
            `UPDATE pets 
             SET happiness = LEAST(100, happiness + 30),
                 hunger = GREATEST(0, hunger - 10),
                 health = LEAST(100, (hunger - 10) / 2 + (happiness + 30) / 2),
                 last_played = NOW()
             WHERE user_id = ?`,
            [userId]
        );
        
        await connection.commit();
        
        // 获取更新后的宠物信息
        const [updatedPets] = await connection.execute(
            'SELECT * FROM pets WHERE user_id = ?',
            [userId]
        );
        
        return successResponse(res, updatedPets[0], '宠物玩得很开心！');
        
    } catch (error) {
        await connection.rollback();
        console.error('玩耍错误:', error);
        return errorResponse(res, '玩耍失败', 500, error);
    } finally {
        connection.release();
    }
};

/**
 * 给宠物改名
 */
const renamePet = async (req, res) => {
    try {
        const userId = req.user.id;
        const { petName } = req.body;
        
        if (!petName || petName.trim().length === 0) {
            return errorResponse(res, '请输入宠物名字', 400);
        }
        
        if (petName.length > 20) {
            return errorResponse(res, '名字太长了，最多20个字符', 400);
        }
        
        await db.execute(
            'UPDATE pets SET pet_name = ? WHERE user_id = ?',
            [petName.trim(), userId]
        );
        
        const [pets] = await db.execute(
            'SELECT * FROM pets WHERE user_id = ?',
            [userId]
        );
        
        return successResponse(res, pets[0], '改名成功！');
        
    } catch (error) {
        console.error('改名错误:', error);
        return errorResponse(res, '改名失败', 500, error);
    }
};

module.exports = {
    getPetInfo,
    feedPet,
    playWithPet,
    renamePet
};

